import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_util/lib_util.dart';

import '../../../../module_common/widgets/skeleton/dapp_tab_skeleton.dart';
import '../../provider/dapp_provider.dart';
import '../dapp_empty.dart';
import 'sliver_tabbar_delegate.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class CoordinatorTabLayout extends StatefulWidget {
  final double? headerHeight;
  final Widget headerView;
  final Widget? tabBarEndWidget;
  final Widget? tabBarTitleWidget;

  final List<String> titles;
  final List<Widget> pages;

  final double labelPaddingLeft;
  final double labelPaddingRight;

  final void Function(double) onScrollTopListen;

  CoordinatorTabLayout(
      {super.key,
      this.headerHeight,
      this.tabBarTitleWidget,
      this.tabBarEndWidget,
      required this.headerView,
      required this.titles,
      required this.pages,
      this.labelPaddingLeft = 0,
      void Function(double)? onScrollTopListen,
      this.labelPaddingRight = 10})
      : onScrollTopListen = onScrollTopListen ?? ((_) {});

  @override
  State<StatefulWidget> createState() {
    return _CoordinatorTabLayoutState();
  }
}

class _CoordinatorTabLayoutState extends State<CoordinatorTabLayout>
    with TickerProviderStateMixin {
  late ScrollController _scrollController;
  late ScrollController _scrollController2;
  late TabController _tabController;
  int _currentIndex = 0;
  bool _needResetTabController = true;

  final List<String> _skeletonTitles = List.generate(6, (index) => "");
  final List<String> _skeletonpages = List.generate(6, (index) => "");

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController2 = ScrollController();
    _scrollController.addListener(_updateOffsetTop);
    _tabController = TabController(length: widget.titles.length, vsync: this);
    _tabController.addListener(_handleTabSelection);
  }

  void _updateOffsetTop() {
    setState(() {
      widget.onScrollTopListen(_scrollController.offset);
    });
  }

  void _handleTabSelection() {
    setState(() {
      _currentIndex = _tabController.index; // 更新当前选中的标签索引
      _needResetTabController = false;
    });
  }

//重新创建tabController，处理数据个数改变后，tab的个数不同问题
  void resetTabController(bool isLoading) {
    if (isLoading) {
      _tabController.dispose();
      _scrollController.removeListener(_updateOffsetTop);
      _scrollController.dispose();
      _scrollController2.dispose();
      _scrollController = ScrollController();
      _scrollController2 = ScrollController();
      _scrollController.addListener(_updateOffsetTop);
      _tabController =
          TabController(length: _skeletonTitles.length, vsync: this);
      _tabController.addListener(_handleTabSelection);
      return;
    }
    if (_needResetTabController &&
        _tabController.length != widget.titles.length) {
      _tabController.dispose();
      _scrollController.removeListener(_updateOffsetTop);
      _scrollController.dispose();
      _scrollController2.dispose();
      _scrollController = ScrollController();
      _scrollController2 = ScrollController();
      _scrollController.addListener(_updateOffsetTop);
      _tabController = TabController(length: widget.titles.length, vsync: this);
      _tabController.addListener(_handleTabSelection);
    } else {
      _needResetTabController = true;
    }
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.removeListener(_updateOffsetTop);
    _scrollController.dispose();
    _scrollController2.dispose();
    super.dispose();
  }

  List<Widget> getTabs(bool isLoding) {
    if (isLoding) {
      return _skeletonTitles
          .map((e) => DAppTabItemSkeleton())
          .toList(growable: false);
    } else {
      return widget.titles
          .map((e) => Container(
                decoration: BoxDecoration(
                  color: widget.titles[_currentIndex] == e
                      ? Color.fromRGBO(134, 103, 254, 0.1)
                      : Color.fromRGBO(246, 246, 246, 1),
                  borderRadius: BorderRadius.circular(8), // 设置圆角半径为 10.0
                ),
                padding: EdgeInsets.only(left: 8, right: 8),
                child: Tab(
                  text: e,
                  height: 30,
                ),
              ))
          .toList(growable: false);
    }
  }

  List<Widget> getPages(bool isLoading) {
    if (isLoading) {
      return _skeletonpages
          .map((e) => _getskeletonpage())
          .toList(growable: false);
    } else {
      return widget.pages;
    }
  }

  Widget _getskeletonpage() {
    return ListView.builder(
        padding: EdgeInsets.only(top: 0),
        physics: const ClampingScrollPhysics(),
        itemCount: 8,
        itemBuilder: (context, index) {
          return DAppTabListPageItemSkeleton();
        });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<DAppProvider>(builder: (context, provider, child) {
      resetTabController(provider.isLoading);
      return NestedScrollView(
        controller: _scrollController,
        headerSliverBuilder: (c, _) => [
          SliverToBoxAdapter(
            child: widget.headerHeight == null || widget.headerHeight == 0
                ? widget.headerView
                : SizedBox(
                    height: widget.headerHeight,
                    child: widget.headerView,
                  ),
          ),
        ],
        body: CustomScrollView(
            controller: _scrollController2,
            physics: const NeverScrollableScrollPhysics(),
            slivers: [
              SliverPersistentHeader(
                  pinned: true,
                  delegate: SliverTabBarDelegate(
                      endWidget: widget.tabBarEndWidget,
                      titleWidget: widget.tabBarTitleWidget,
                      isEmpty: provider.isLoading
                          ? _skeletonTitles.isEmpty
                          : widget.titles.isEmpty,
                      tabBar: TabBar(
                        dividerColor: Colors.transparent,
                        tabAlignment: TabAlignment.start,
                        isScrollable: true,
                        labelColor: AppColors.c_1D0061,
                        unselectedLabelColor: Color.fromRGBO(134, 131, 145, 1),
                        indicatorColor: Colors.white,
                        indicatorPadding: EdgeInsets.only(
                            left: widget.labelPaddingLeft.w,
                            right: widget.labelPaddingRight.w,
                            bottom: 0),
                        tabs: getTabs(provider.isLoading),
                        labelPadding: EdgeInsets.only(
                            left: widget.labelPaddingLeft.w,
                            right: widget.labelPaddingRight.w),
                        labelStyle: TextStyle(
                            fontWeight: FontWeight.w400, fontSize: 12.sp),
                        controller: _tabController,
                      ),
                      backgroundColor: Colors.white)),
              SliverFillRemaining(
                child: (!provider.isLoading && widget.titles.isEmpty)
                    ? Container(
                        color: Color.fromRGBO(255, 255, 255, 1),
                        child: DAppEmpty(title: 'Empty data'),
                      )
                    : Container(
                        color: Colors.white,
                        height: double.infinity,
                        child: TabBarView(
                            physics: NeverScrollableScrollPhysics(),
                            controller: _tabController,
                            children: getPages(provider.isLoading)),
                      ),
              ),
            ]),
      );
    });
  }
}
